package servlet;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.bson.Document;
import org.bson.types.ObjectId;


/**
 * Created by mmdzm on 2017/4/27.
 */
@WebServlet(description = "uploadProcess", urlPatterns = { "/manager/userManage/UploadServlet" })
public class UploadServlet extends HttpServlet{

    private static final long serialVersionUID = 7042756416806244618L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	
        String adjunctname = null;
        String fileDir = getServletContext().getRealPath("/upload");
        System.out.println("fileDir: " + fileDir);
        // 指定上传文件的保存地址
        String message = "文件上传成功";
        String address = "";
       // request.setCharacterEncoding("UTF-8");
        
        if (ServletFileUpload.isMultipartContent(request)) { // 判断是否是上传文件
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(20 * 1024); // 设置内存中允许存储的字节数
            ServletFileUpload upload = new ServletFileUpload(factory); // 创建新的上传文件句柄
			upload.setHeaderEncoding("utf-8"); // 防止中文乱码
			
            int size = 10 * 1024 * 1024; // 指定上传文件的大小
            List formlists = null; // 创建保存上传文件的集合对象
            try {
                formlists = upload.parseRequest(request); // 获取上传文件集合
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator iter = formlists.iterator(); // 获取上传文件迭代器
            while (iter.hasNext()) {
                FileItem formitem = (FileItem) iter.next(); // 获取每个上传文件
                if (!formitem.isFormField()) { // 忽略不是上传文件的表单域
                    String name = formitem.getName(); // 获取上传文件的名称
                    if (formitem.getSize() > size) { // 如果上传文件大于规定的上传文件的大小
                        message = "您上传的文件太大，请选择不超过10M的文件";
                        break; // 退出程序
                    }
                    String adjunctsize = new Long(formitem.getSize())
                            .toString(); // 获取上传文件的大小
                    if ((name == null) || (name.equals(""))
                            && (adjunctsize.equals("0"))) // 如果上传文件为空
                        continue; // 退出程序
                    adjunctname = name.substring(name.lastIndexOf("\\") + 1,
                            name.length());
                    address = fileDir + "/" + adjunctname; // 创建上传文件的保存地址
                    File saveFile = new File(address); // 根据文件保存地址，创建文件
                    try {
                    	formitem.write(saveFile);                   	
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                else {    // 不是file类型的话，就利用getFieldName判断name属性获取相应的值
                	if("users".equals(formitem.getFieldName())){
                		request.setAttribute("fileDir", address);
                	    request.getRequestDispatcher("userManageServlet?method=batchAdd&&type=s").forward(request, response);
                	}else if("usert".equals(formitem.getFieldName())){
                		request.setAttribute("fileDir", address);
                	    request.getRequestDispatcher("userManageServlet?method=batchAdd&&type=t").forward(request, response);
                	}else if("courseclass".equals(formitem.getFieldName())){
                		String name = address.substring(address.lastIndexOf("/")+1,address.length()); 
                	    response.sendRedirect("/jspbighomework/manager/courseclass/managercourseclassServlet?method=managerbatchadd&&filename="+name);
                	}else if("template".equals(formitem.getFieldName())){
                		Iterator iterator = formlists.iterator(); // 获取上传文件迭代器
                		String typeid = null, typename = null;
                        while (iterator.hasNext()) {
                            FileItem form = (FileItem) iterator.next(); // 获取每个上传文件
                            if (form.isFormField()) {                          	
                        		if("typeid".equals(form.getFieldName())) {
                        			typeid = form.getString("UTF-8").trim(); 
                        		}
                        		if("typename".equals(form.getFieldName())) {
                        			typename = form.getString().trim(); 
                        		}                     	
                            }
                        }
                		String name = address.substring(address.lastIndexOf("/")+1,address.length());   
                		String url = "/jspbighomework/manager/TeachingMaterialsTemplate/teachingMaterialsTemplateServlet?method=add&&name="+java.net.URLEncoder.encode(name,"UTF-8")+
                				"&&typeid="+typeid+
                				"&&typename="+typename;
                	    response.sendRedirect(url);
                	}else if("templateReplace".equals(formitem.getFieldName())){
                		Iterator iterator = formlists.iterator(); // 获取上传文件迭代器
                		String templateid = null;
                        while (iterator.hasNext()) {
                            FileItem form = (FileItem) iterator.next(); // 获取每个上传文件
                            if (form.isFormField()) {                          	
                        		if("templateid".equals(form.getFieldName())) {
                        			templateid = form.getString("UTF-8").trim(); 
                        		}                 	
                            }
                        }
                		String name = address.substring(address.lastIndexOf("/")+1,address.length());  
                		String url = "/jspbighomework/manager/TeachingMaterialsTemplate/teachingMaterialsTemplateServlet?method=replace&&name="+java.net.URLEncoder.encode(name,"UTF-8")+
                				"&&templateid="+templateid;
                	    response.sendRedirect(url);
                	}else if("task".equals(formitem.getFieldName())){
                		Iterator iterator = formlists.iterator(); // 获取上传文件迭代器
                		String taskid = null;
                        while (iterator.hasNext()) {
                            FileItem form = (FileItem) iterator.next(); // 获取每个上传文件
                            if (form.isFormField()) {                          	
                        		if("taskid".equals(form.getFieldName())) {
                        			taskid = form.getString("UTF-8").trim(); 
                        		}                  	
                            }
                        }
                        String uploadfilename = address.substring(address.lastIndexOf("/")+1,address.length());
                		response.sendRedirect("/jspbighomework/teacher/task/taskServlet?method=upload&&uploadfilename="+java.net.URLEncoder.encode(uploadfilename,"UTF-8")+"&&taskid="+taskid);
                	}else {
                		//TODO其他信息批量处理
                	}  
                }
            }
        }

    }

    public void init() throws ServletException {
    }
}
